const { createUser, getUserInfo, UpdateUserinfo } = require('../service/user_service')


//导入本地配置
const { JWT_SECRET } = require('../config/config_default')

//导入jwt
var jwt = require('jsonwebtoken');
const { userRegister } = require('../constant/error_type');
const { Json } = require('sequelize/lib/utils');
class UserController {
    //用户注册
    async register(ctx, next) {
        //1.获取数据
        // console.log(ctx.request.body);
        const { user_name, password } = ctx.request.body
        try {
            const res = await createUser(user_name, password);
            //3返回结果
            ctx.body = {
                code: '0',
                message: '用户注册成功',
                result: {
                    id: res.id,
                    // user_name: res.user_name
                }
            }
        } catch (error) {
            console.log(error);
            ctx.app.emit('error', userRegister, ctx)
        }
        //2.操作数据库

    }

    //用户登录
    async login(ctx, next) {

        const { user_name } = ctx.request.body

        //1.获取用户信息(token中的playload,记录id,user_name,is_admin)
        try {
            //剔除密码 ,剩余参数交给res
            const { password, ...res } = await getUserInfo({ user_name })
            ctx.body = {
                code: 0,
                message: '用户登陆成功',
                result: {
                    //expiresIn生效时间   (加密参数,加密密钥,加密时间)
                    token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
                }
            }

        } catch (error) {
            console.error('登录失败');


        }
    }

    //用户修改密码
    async ChangePassword(ctx, next) {
        // 1.获取数据
        const { id } = ctx.state.user
        const { password } = ctx.request.body

        //2.操作数据库 
        const res = await UpdateUserinfo({ id, password })
        //3.返回结果
        if (res) {
            ctx.body = {
                code: '0',
                message: '修改密码成功',
                result:''
            }
        }
        else{
            ctx.body = {
                code: '100007',
                message: '修改密码失败',
                result:''
            }
        }

    }


}

module.exports = new UserController()
